package com.kfm.servlet;

import com.kfm.entity.User;
import com.kfm.service.UserService;
import com.kfm.util.Contains;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理登录请求

        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");

        // 校验验证码
        if (!CaptchaUtil.ver(captcha, request)){
            // 验证码输入错误
            request.setAttribute("msg", "验证码输入错误");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        // 将 session 中之前的 验证码清空掉
        CaptchaUtil.clear(request);

        User loginUser = service.login(username, password);

        if (loginUser != null){
            // 登录成功
            // 把用户信息存储到 session 中
            request.getSession().setAttribute(Contains.LOGIN_USER, loginUser);

            // 重定向到首页
            response.sendRedirect("index");
        } else {
            request.setAttribute("msg", "用户名或密码错误");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}
